﻿using WLFramework.DataAccess;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using fastJSON;

namespace SampleSite.ajax
{
    /// <summary>
    /// GetTreeNodes 的摘要说明
    /// </summary>
    public class GetTreeNodes : IHttpHandler
    {

        private class TreeNode
        {
            public int id { get; set; }
            public string name { get; set; }
            public string ename { get; set; }
            public List<TreeNode> children { get; set; }
        }

        public void ProcessRequest (HttpContext context)
		{
			try {
				context.Response.ContentType = "text/plain";
				PermissionCommand command = DataAccessor.CreateInstance<PermissionCommand> ();
				var list = command.SYS_GetOrg ().ToList ();

				List<TreeNode> nodes = new List<TreeNode> ();
				int depths = list.Max (k => k.Depth) + 1;
				Dictionary<int, TreeNode> parents = null;
				Dictionary<int, TreeNode> currents = null;
				for (int i = 0; i < depths; i++) {
					int j = 0;
					currents = new Dictionary<int, TreeNode> ();
					while (j < list.Count) {
						if (i == list [j].Depth) {
							TreeNode node = new TreeNode ()
                        {
                            id = list[j].O_ID,
                            name = list[j].O_CName,
                            ename = list[j].O_EName,
                            children = new List<TreeNode>()
                        };

							if (list [j].Depth == 0) {
								nodes.Add (node);
							}

							currents [node.id] = node;

							if (list [j].O_ParentID > 0 &&
								parents != null &&
								parents.ContainsKey (list [j].O_ParentID.Value)) {
								parents [list [j].O_ParentID.Value].children.Add (node);
							}

							list.RemoveAt (j);
						} else {
							j++;
						}
					}

					parents = currents;
					currents = null;
				}

				context.Response.Write (JSON.Instance.ToJSON (nodes));
			} catch(Exception ex) {
				context.Response.Write(ex.Message);
			}
		}

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}